var core = require('utils/core.js');

// 检测统计用户行为  统计代码
import Matomo from './utils/tongji'
const pageTitles = {
  "app/launch": '启动加载页',
  'pages/index/index': '商城首页',
  "pages/authloading/authloading": '授权登陆中转页',
  "pages/active/index": '会员试用',
  "pages/custom/index": '自定义页面',
  "pages/goods/searchlist/index": '搜索结果页',
  "pages/gettoken/index": '获取token',
  "pages/goods/detail/index": '商品详情页',
  "pages/goods/index/index": '全部商品页',
  "pages/goods/searchlist/searchlist": '搜索',
  "pages/maintain/index": '系统维护页',
  "pages/member/bind/index": '绑定手机号',
  "pages/member/cart/index": '购物车',
  "pages/member/coupon/index": '优惠券',
  "pages/member/favorite/index": '我的收藏',
  "pages/member/index/index": '个人中心',
  "pages/message/auth/index": '授权登陆',
  "pages/order/create/index": '订单结算页',
  "pages/order/detail/index": '订单详情页',
  "pages/order/express/index": '物流详情',
  "pages/order/index": '我的订单',
  "pages/web/index": '外部网站中转'
}
const reportUrl = 'https://cccstore.totole.com.cn/tongji/matomo.php'
const siteId = '34'
Matomo.initTracker(reportUrl, siteId, {
  pageTitles
})
// SDK需要先通过init初始化才能正常使用
let sr = require('./utils/sdk.js').init({
  appid: 'wxb82db19abaea3adf', // 微信小程序 appid，以 wx 开头
  token: 'bief8a0e61d4fd4596', // token是有数 appid，以 bi 开头，值为 https://srdata.tencent.com/ 中的密钥管理_APP ID
  usePlugin: true,
  proxyComponent: true,
  openSdkShareDepth: true,
  autoTrack: true,
  openAutoTrackOpenId: true,
  proxyPage: true
})
App({
  sr, // 挂载到App实例上
  onShow: function () {
    // this.onLaunch();
  },
  globalData: {
    extra: '',
    goodsType_for_switch_tab: '',
    isShowCustomerService: false, //在线客服
    isShowPhoneService: false, //客服电话
  },
  // 检查最新版本
  checkUpdate: function () {
    let $this = this
    try {
      var updateManager = wx.getUpdateManager();
      var that = this;
      let userinfo = $this.getCache('userinfo')
      if (userinfo) {
        $this.sr.setUser({
          open_id: userinfo.openid,
          union_id: userinfo.unionid
        })
      }
      updateManager.onUpdateReady(function () {
        updateManager.applyUpdate()
      })
    } catch (e) {

    }
  },
  onLaunch: function (options) {
    let path = options.path
    //不允许直接进入的页面
    let list = [
      "pages/order/create/index                                                                                                  ",
    ]
    list.forEach(ele => {
      if (path == ele) {
        wx.switchTab({
          url: '/pages/gift/index',
        })
      }
    })
    console.log(options)
    if (options.query.mid) {
      wx.setStorageSync('helpid', options.query.mid)
    }
    // wx.hideTabBar({
    //   // animation: true,
    // })
    let date = new Date();
    this.checkUpdate()
    let $this = this;
    wx.getSystemInfo({
      success: function (res) {
        var model = res.model;
        var iponeX = model.indexOf("iPhone X")
        if (iponeX == '0') {
          $this.setCache("isIpx", res.model);
        } else {
          $this.setCache("isIpx", '');
        }
      }
    })
    wx.getSystemInfo({ //  获取页面的有关信息
      success: function (res) {
        // wx.setStorageSync('systemInfo', res)

        var ww = res.windowWidth;
        var hh = res.windowHeight;
        $this.globalData.ww = ww;
        $this.globalData.hh = hh;
      }
    });
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline'],
      success(res) {
        console.log('showShareMenu', res);
      }
    })
    this.getConfig();
  },
  getConfig: function () {
    if (this.globalData.api !== null) {
      return {
        api: this.globalData.api,
        approot: this.globalData.approot,
        appid: this.globalData.appid
      };
    }
    var ext = wx.getExtConfigSync();
    this.globalData.api = ext.config.api;
    this.globalData.approot = ext.config.approot;
    this.globalData.appid = ext.config.appid;
    return ext.config;
  },
  //检查小程序是否授权
  checkAuth: function () {
    var userinfo = this.getCache('userinfo')
    if (!userinfo) {
      return false;
    } else {
      return true;
    }
  },
  //不知道用处
  requirejs: function (jsname) {
    return require('utils/' + jsname + '.js');
  },
  //得到缓存
  getCache: function (key, defaultValue) {
    var time = (+new Date()) / 1000,
      data = '';
    time = parseInt(time);
    try {
      // data = wx.getStorageSync(key + this.globalData.appid);
      var keyCache = this.globalData.currPlatform + "_" + key + "_" + this.globalData.appid
      data = wx.getStorageSync(keyCache);
      data = data.value;
    } catch (e) {
      data = typeof (defaultValue) === 'undefined' ? '' : defaultValue;
    }
    data = data || '';
    return data;
  },
  //设置缓存
  setCache: function (key, value, expire) {
    var time = (+new Date()) / 1000,
      rt = true;
    var data = {
      expire: expire ? time + parseInt(expire) : 0,
      value: value
    };
    try {
      wx.setStorageSync(key + this.globalData.appid, data);
      var keyCache = this.globalData.currPlatform + "_" + key + "_" + this.globalData.appid
      wx.setStorageSync(keyCache, data);
    } catch (e) {
      rt = false;
    }
    return rt;
  },
  //移除缓存
  removeCache: function (key) {
    var rt = true;
    try {
      wx.removeStorageSync(key + this.globalData.appid);
      var keyCache = this.globalData.currPlatform + "_" + key + "_" + this.globalData.appid;
      wx.removeStorageSync(keyCache);
    } catch (e) {
      rt = false;
    }
    return rt;
  },
  //在黑名单中时调用
  close: function () {
    this.globalDataClose.flag = true;
    wx.reLaunch({
      url: '/pages/index/index',
    })
  },
  //不知道用处
  getSet: function () {
    var $this = this;
    var cacheset = $this.getCache("cacheset");
    setTimeout(function () {
      var cacheset = $this.getCache("cacheset");
      core.get('cacheset', {
        version: cacheset.version
      }, function (result) {
        if (result.update) {
          $this.setCache("cacheset", result.data);
        }
      });
    }, 10);
  },
  //不知道用处
  url: function (options) {
    options = options || {};
    var arg = {},
      mid = '',
      merchid = '',
      user = this.getCache('usermid');
    mid = options.mid || '';
    merchid = options.merchid || '';
    if (user != '') {
      if (user.mid == '' || typeof user.mid == 'undefined') {
        arg.mid = mid;
        arg.merchid = user.merchid;
      }
      if (user.merchid == '' || typeof user.merchid == 'undefined') {
        arg.merchid = merchid;
        arg.mid = user.mid;
      }
    } else {
      arg.mid = mid;
      arg.merchid = merchid;
    }
    this.setCache('usermid', arg, 7200);
  },
  /*再次发起授权*/
  impower: function (limit, msg, route) {
    wx.getSetting({
      success: function (res) {
        var limits = res.authSetting['scope.' + limit];
        if (!limits) {
          wx.showModal({
            title: '用户未授权',
            content: '您点击了拒绝授权，暂时无法' + msg + '    ~',
            confirmText: '去设置',
            success: function (res) {
              if (res.confirm) {
                wx.openSetting({
                  success: function (res) { }
                })
              } else {
                if (route == 'route') {
                  wx.switchTab({
                    url: '/pages/index/index'
                  })
                } else if (route == 'details') {
                  //停留在当前页面
                } else {
                  wx.navigateTo({
                    url: '/pages/index/index'
                  })
                }

              }
            }
          })
        }
      }
    })
  },
  // 小程序店铺配置，小程序是否维护
  miniprogram(callback) {
    let $this = this
    if (this.getCache('userinfo').id) {
      core.post($this.globalData.newApi + 'api/member/miniprogram', {}, function (res) {
        if (res.isVindicate == 0) {
          wx.redirectTo({
            url: '/pages/maintain/index',
            success: function (res) { },
            fail: function (res) { },
            complete: function (res) { },
          })
        } else {
          $this.globalData.isShowCustomerService = false
          $this.globalData.isShowPhoneService = false
          if (res.isShowCustomerService == 1) {
            $this.globalData.isShowCustomerService = true
          }
          if (res.isShowPhoneService == 1) {
            $this.globalData.isShowPhoneService = true
          }
          return callback(res)
        }
      })
    }
  },
  globalDataClose: {
    flag: false,
  },
  globalData: {
    appid: "wxb82db19abaea3adf",
   // newApi: 'https://cccstore.totole.com.cn/',
     newApi: 'http://localhost:8092/api/single/',
    // newApi: 'https://totoleec.widiazine.cn/',
    tenantId: 1,
    currPlatform: "PRO",
    shopId: 1,
  }
})